package com.google.code.mukiranaproject.script;

import com.google.code.mukiranaproject.model.Lance;
import com.google.code.mukiranaproject.netlib.*;
import com.google.code.mukiranaproject.persistencia.dao.LanceDao;

import java.io.IOException;
import java.io.StringReader;
import java.net.*;
import java.util.ArrayList;

import javax.swing.text.html.HTMLEditorKit;

public class Script {
	public static final String WEB_ADDRESS = "http://www.mukirana.com.br";
//	public static final String WEB_ADDRESS = "http://127.0.0.1:8080/";

	public static final String ID_LEILAO = "328";
	public static final String ITEM = "/auctions/"+ID_LEILAO+"-pacote-de-200-lances-leilao";
//	public static final String ITEM = "SATA/teste.html";
	public static final String DIV_ID = "last_bids_auction_"+ID_LEILAO;
	
	private ArrayList<Lance> lancesComputados;
	
	private LanceDao dao = new LanceDao();
	
	public static void main(String [] args) throws InterruptedException{
		Script s = new Script();
		s.lancesComputados = new ArrayList<Lance>();
		
		while (true) {
			try {
				System.out.println("conectando no site");
				URLHelper uh = new URLHelper(WEB_ADDRESS + ITEM);
				s.parseHTML(uh.contentToString());
				uh.close();
			} catch (MalformedURLException ex) {
				System.out.println("URL inválida.");
				ex.printStackTrace();
			} catch (IOException ex) {
				System.out.println("Erro na conexão");
				ex.printStackTrace();
			}
			
			Thread.sleep(1500);
		}
	}
	
	private void parseHTML(String data) throws IOException, InterruptedException {
		System.out.println("parse");
		LancesParserCallback lpc = new LancesParserCallback(DIV_ID, ID_LEILAO);
		StringReader r = new StringReader(data);
		HTMLEditorKit.Parser parser = new HTMLParser().getParser();
		parser.parse(r, lpc, true);
		
		ArrayList<Lance> lances = lpc.getLances();
		
		for (Lance lance : lances) {
			if (!dao.lanceExistente(lance)) {
				dao.incluirLance(lance);
				System.out.print(lance.getUsuario() + " ");
				System.out.println(lance.getCentavos());
			}
		}
	}
}
